import OSSFileModel from './OSSFileModel'

/**
 * 列表加载数据封装
 */
class YBListLoad {
  // 构造方法
  constructor(bucket = '', prefix = '') {
    /**
     * 数据数组
     * @type {Array}
     */
    this.dataArr = []
    /**
     * 是否加载完成
     * @type {boolean}
     */
    this.finish = false
    /**
     * 当前加载状态
     * @type {boolean}
     */
    this.loading = false
    /**
     * bucket
     * @type {string}
     */
    this.bucket = bucket
    /**
     * 文件前缀
     * @type {string}
     */
    this.prefix = prefix
    /**
     * 分页加载个数
     * @type {number}
     */
    this.pageSize = 30
  }

  /**
   * 加载数据
   * @returns {Promise<any>}
   */
  loadData() {
    return new Promise((resolve, reject) => {
      if (!this.loading && !this.finish) {
        this.loading = true
        const lastKey = this.dataArr.length > 0 ? this.dataArr[this.dataArr.length - 1].name : ''
        OSSFileModel.loadModels(lastKey, {
          bucket: this.bucket,
          prefix: this.prefix
        }).then((dataArr) => {
          this.finish = dataArr.length < this.pageSize
          this.dataArr = this.dataArr.concat(dataArr)
          resolve(this.dataArr)
        }).catch((err) => {
          reject(err)
        }).finally(() => {
          this.loading = false
        })
      } else {
        const p = { load: true }
        reject(p)
      }
    })
  }

  /**
   * 清除数据
   */
  clearData() {
    this.dataArr = []
    this.loading = false
    this.finish = false
  }

  /**
   * 删除指定的数据
   * @param index
   */
  removeWithIndex(index) {
    this.dataArr.splice(index, 1)
  }
}

export default YBListLoad
